<template>
  <div>
    <main-layout2 :search-word="pageData.searchKey" :flag="pageData.flag">
      <!-- 标题插槽 -->
      <template #title>
        <i class="iconfont icon-chanpin"></i>
        <label class="main-layout-title">产品管理</label>
      </template>

      <!-- 操作按钮 -->
      <template #operation>
        <el-button type="primary" @click="openShopDialog">添加汽车店</el-button>
      </template>

      <!-- 搜索框 -->
      <template #search>
        <el-input
          v-model="pageData.searchKey"
          style="width: 240px"
          :placeholder="pageData.searchPrompt"
          :prefix-icon="Search"
        />
      </template>

      <!-- 菜单选项卡 -->
      <template #menu>
        <label style="font-size: 13px">显示：</label>
        <el-button :type="pageData.activeTab === 1 ? 'primary' : ''"
          >汽车店</el-button
        >
      </template>

      <!-- 内容区域 -->
      <template #sub>
        <div class="fill">
          <div class="table">
            <el-table
              v-loading="pageData.isLoading"
              element-loading-text="数据加载中..."
              empty-text="暂无数据"
              :row-key="(row: any) => row.id"
              stripe
              @row-click="(row: any)=>{
                router.push('/carShop/detail/'+row.id);
              }"
              :data="pageData.shopList"
              class="fill"
            >
              <!-- 完整表格列定义 -->
              <el-table-column
                fixed="left"
                prop="name"
                label="店铺名称"
                show-overflow-tooltip
                width="200"
                sortable
              />
              <el-table-column
                prop="typeName"
                label="店铺类型"
                width="150"
                sortable
              />
              <el-table-column prop="isOpen" label="是否营业" width="150">
                <template #default="{ row }">{{
                  row.isOpen ? "是" : "否"
                }}</template>
              </el-table-column>
              <el-table-column
                prop="operatingHours"
                label="营业时间"
                width="150"
                sortable
              />
              <el-table-column
                prop="openingDateStr"
                label="开业日期"
                width="150"
                sortable
              />
              <el-table-column
                prop="managerName"
                label="店长姓名"
                show-overflow-tooltip
                width="150"
                sortable
              />
              <el-table-column prop="isSelf" label="是否自营" width="150">
                <template #default="{ row }">{{
                  row.isSelf ? "是" : "否"
                }}</template>
              </el-table-column>
              <el-table-column
                prop="phone"
                label="联系电话"
                width="150"
                sortable
              />
              <el-table-column
                prop="email"
                label="邮箱"
                show-overflow-tooltip
                width="150"
                sortable
              />
              <el-table-column
                prop="website"
                label="网址"
                show-overflow-tooltip
                width="150"
                sortable
              />
              <el-table-column
                prop="province"
                label="省"
                width="100"
                sortable
              />
              <el-table-column prop="city" label="市" width="100" sortable />
              <el-table-column
                prop="county"
                label="县/区/市"
                show-overflow-tooltip
                width="100"
                sortable
              />
              <el-table-column
                prop="address"
                label="店铺地址"
                show-overflow-tooltip
                width="200"
                sortable
              />
              <el-table-column
                prop="postalCode"
                label="邮政编码"
                width="150"
                sortable
              />
              <el-table-column
                prop="createdAtStr"
                label="数据创建时间"
                width="150"
                sortable
              />
              <el-table-column
                prop="updatedAtStr"
                label="数据最后更新时间"
                width="180"
                sortable
              />
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              background
              v-model:page-size="pageData.pagination.pageSize"
              v-model:current-page="pageData.pagination.currentPage"
              :page-size-options="[10, 20, 30, 40, 50]"
              layout="prev, pager, next, jumper, sizes"
              :total="pageData.totalCount"
            />
          </div>
        </div>
      </template>
    </main-layout2>

    <!-- 添加汽车店对话框 -->
    <el-dialog
      width="80%"
      v-model="dialogVisible.shopForm"
      title="添加汽车店"
      align-center
      @closed="resetShopForm"
    >
      <el-scrollbar class="scroll-bar">
        <el-form
          ref="shopFormRef"
          :model="formData.shop"
          label-width="80px"
          class="form"
          :inline="true"
          :rules="formRules.shop"
        >
          <el-form-item label="名称" prop="name" class="form-item">
            <el-input v-model="formData.shop.name" :maxlength="127" />
          </el-form-item>

          <el-form-item label="类型" prop="type" class="form-item">
            <el-select
              v-model="formData.shop.type"
              :loading="formData.shop.categoryLoading"
              placeholder="请选择类型"
            >
              <el-option
                v-for="item in formData.shop.categoryList"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="营业时间"
            prop="operatingHours"
            class="form-item2"
          >
            <el-time-select
              v-model="formData.shop.startTime"
              style="width: 240px; margin-right: 30px"
              :max-time="formData.shop.endTime"
              placeholder="开始时间"
              start="08:30"
              step="00:15"
              end="18:30"
              @change="updateOperatingHours"
            />
            <el-time-select
              v-model="formData.shop.endTime"
              style="width: 240px"
              :min-time="formData.shop.startTime"
              placeholder="结束时间"
              start="08:30"
              step="00:15"
              end="18:30"
              @change="updateOperatingHours"
            />
          </el-form-item>

          <el-form-item label="电话" prop="phone" class="form-item">
            <el-input v-model="formData.shop.phone" :maxlength="11" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email" class="form-item">
            <el-input v-model="formData.shop.email" :maxlength="100" />
          </el-form-item>

          <el-form-item label="邮编" prop="postalCode" class="form-item">
            <el-input v-model="formData.shop.postalCode" :maxlength="6" />
          </el-form-item>

          <el-form-item
            label="地区"
            prop="provinceCityCounty"
            class="form-item"
          >
            <el-cascader
              v-model="formData.shop.provinceCityCounty"
              :options="regionOptions"
              placeholder="请选择地区"
            />
          </el-form-item>

          <el-form-item label="详细地址" prop="address" class="form-item">
            <el-input v-model="formData.shop.address" :maxlength="127" />
          </el-form-item>

          <el-form-item label="开业日期" prop="openingDate" class="form-item">
            <el-date-picker
              v-model="formData.shop.openingDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>

          <el-form-item label="店主姓名" prop="managerName" class="form-item">
            <el-input v-model="formData.shop.managerName" :maxlength="20" />
          </el-form-item>

          <el-form-item label="网站" prop="website" class="form-item2">
            <el-input v-model="formData.shop.website" :maxlength="255" />
          </el-form-item>

          <el-form-item label="店面图片" prop="shopImage" class="form-item2">
            <el-upload
              v-model:file-list="formData.shop.shopImage.images"
              :auto-upload="false"
              list-type="picture-card"
              :on-preview="formData.shop.shopImage.handlePictureCardPreview"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="formData.shop.shopImage.dialogVisible">
              <img
                w-full
                :src="formData.shop.shopImage.dialogImageUrl"
                alt="Preview Image"
              /> </el-dialog
          ></el-form-item>
          <el-form-item
            label="营业执照"
            prop="certificateImage"
            class="form-item2"
          >
            <el-upload
              v-model:file-list="formData.shop.certificateImage.images"
              :auto-upload="false"
              list-type="picture-card"
              :on-preview="
                formData.shop.certificateImage.handlePictureCardPreview
              "
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="formData.shop.certificateImage.dialogVisible">
              <img
                w-full
                :src="formData.shop.certificateImage.dialogImageUrl"
                alt="Preview Image"
              />
            </el-dialog>
          </el-form-item>

          <el-form-item label="是否自营" prop="isSelf" class="form-item">
            <el-switch
              v-model="formData.shop.isSelf"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>

          <el-form-item label="营业状态" prop="isOpen" class="form-item">
            <el-switch
              v-model="formData.shop.isOpen"
              :active-value="1"
              :inactive-value="0"
              active-text="营业中"
              inactive-text="休息中"
            />
          </el-form-item>

          <el-form-item label="备注" prop="notes" class="form-item2">
            <el-input
              v-model="formData.shop.notes"
              type="textarea"
              :maxlength="250"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <el-button type="primary" @click="submitShopForm">提交</el-button>
      </template>
    </el-dialog>

    <!-- 账号信息对话框 -->
    <el-dialog
      v-model="dialogVisible.accountInfo"
      :before-close="(done:any)=> { confirmBox('确认关闭？', done) }"
      title="账号信息"
    >
      <div class="account-info">
        <div class="info-item">
          <span>账号：</span>
          <el-tag>{{ generatedAccount.account }}</el-tag>
        </div>
        <div class="info-item">
          <span>密码：</span>
          <el-tag>{{ generatedAccount.password }}</el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Search } from "@element-plus/icons-vue";
import { pcaTextArr } from "element-china-area-data";
import MainLayout2 from "@/components/MainLayout2.vue";
import { getCarShopPagination, addCarShop } from "@/api/carShop";
import { getDictionaryListByDictionaryTypeKey } from "@/api/dictionary";
import { confirmBox, toast } from "@/tools/tools";

interface ShopForm {
  name: string;
  type: string;
  startTime: string;
  endTime: string;
  operatingHours: string;
  phone: string;
  email: string;
  postalCode: string;
  provinceCityCounty: string[];
  address: string;
  openingDate: string;
  managerName: string;
  website: string;
  isSelf: number;
  isOpen: number;
  notes: string;
  categoryList: any[];
  categoryLoading: boolean;
  shopImage: any;
  certificateImage: any;
}

interface PageState {
  isLoading: boolean;
  shopList: any[];
  pagination: {
    currentPage: number;
    pageSize: number;
  };
  totalCount: number;
  searchKey: string;
  searchPrompt: string;
  activeTab: number;
  flag: boolean;
}

const router = useRouter();
const route = useRoute();

// 页面状态
const pageData = reactive<PageState>({
  isLoading: false,
  shopList: [],
  pagination: {
    currentPage: 1,
    pageSize: 10,
  },
  totalCount: 0,
  searchKey: "",
  searchPrompt: "店铺名称/店长姓名",
  activeTab: 1,
  flag: false,
});

// 表单数据
const formData = reactive({
  shop: {
    name: "",
    type: "",
    startTime: "",
    endTime: "",
    operatingHours: "",
    phone: "",
    email: "",
    postalCode: "",
    provinceCityCounty: [],
    address: "",
    openingDate: "",
    managerName: "",
    website: "",
    isSelf: 0,
    isOpen: 1,
    notes: "",
    categoryList: [],
    categoryLoading: false,
    shopImage: {
      handlePictureCardPreview: (uploadFile: any) => {
        formData.shop.shopImage.dialogImageUrl = uploadFile.url!;
        formData.shop.shopImage.dialogVisible = true;
      },
      images: [],
      dialogVisible: false,
      dialogImageUrl: "",
    },
    certificateImage: {
      handlePictureCardPreview: (uploadFile: any) => {
        formData.shop.certificateImage.dialogImageUrl = uploadFile.url!;
        formData.shop.certificateImage.dialogVisible = true;
      },
      images: [],
      dialogVisible: false,
      dialogImageUrl: "",
    },
  } as ShopForm,
});

// 验证规则
const formRules = reactive({
  shop: {
    name: [
      { required: true, message: "请输入名称", trigger: "blur" },
      { min: 2, max: 50, message: "长度在2-50个字符", trigger: "blur" },
    ],
    type: [{ required: true, message: "请选择类型", trigger: "change" }],
    phone: [
      { required: true, message: "请输入电话", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入有效手机号" },
    ],
    email: [
      { required: true, message: "请输入邮箱", trigger: "blur" },
      { type: "email", message: "请输入有效邮箱" },
    ],
    postalCode: [
      { required: true, message: "请输入邮编", trigger: "blur" },
      { pattern: /^[1-9]\d{5}$/, message: "请输入有效邮编" },
    ],
    address: [{ required: true, message: "请输入地址", trigger: "blur" }],
    provinceCityCounty: [
      { required: true, message: "请选择地区", trigger: "change" },
    ],
    openingDate: [
      { required: true, message: "请选择开业日期", trigger: "change" },
    ],
    managerName: [
      { required: true, message: "请输入店主姓名", trigger: "blur" },
    ],
    website: [{ required: true, message: "请输入网站", trigger: "blur" }],
  },
});

// 对话框状态
const dialogVisible = reactive({
  shopForm: false,
  accountInfo: false,
});

// 生成的账号信息
const generatedAccount = reactive({
  account: "",
  password: "",
});

// 地区选项
const regionOptions = pcaTextArr;

// 表单引用
const shopFormRef = ref<any>(null);

// 方法实现
const fetchShopList = async () => {
  pageData.isLoading = true;
  try {
    const params = {
      page: pageData.pagination.currentPage,
      limit: pageData.pagination.pageSize,
      key: pageData.searchKey,
    };
    const res = await getCarShopPagination(params);
    if (res.code === 0) {
      pageData.shopList = res.data.data;
      pageData.totalCount = res.data.total;
    }
  } finally {
    pageData.isLoading = false;
  }
};

const loadShopCategories = async () => {
  formData.shop.categoryLoading = true;
  try {
    const res = await getDictionaryListByDictionaryTypeKey(
      "car_shop_categorys"
    );
    if (res.code === 0) {
      formData.shop.categoryList = res.data;
    }
  } finally {
    formData.shop.categoryLoading = false;
  }
};
const openShopDialog = () => {
  dialogVisible.shopForm = true;
};
const updateOperatingHours = () => {
  formData.shop.operatingHours = `${formData.shop.startTime}-${formData.shop.endTime}`;
};

const submitShopForm = async () => {
  try {
    const valid = await shopFormRef.value.validate();
    if (!valid) return;
    const form = new FormData();
    form.append("name", formData.shop.name);
    form.append("type", formData.shop.type);
    form.append(
      "operatingHours",
      formData.shop.startTime + "-" + formData.shop.endTime
    );
    form.append("phone", formData.shop.phone);
    form.append("email", formData.shop.email);
    form.append("postalCode", formData.shop.postalCode);
    form.append("province", formData.shop.provinceCityCounty[0]);
    form.append("city", formData.shop.provinceCityCounty[1]);
    form.append("county", formData.shop.provinceCityCounty[2]);
    form.append("address", formData.shop.address);
    form.append("openingDate", formData.shop.openingDate.toLocaleString());
    form.append("managerName", formData.shop.managerName);
    form.append("website", formData.shop.website);
    form.append("isSelf", formData.shop.isSelf.toString());
    form.append("isOpen", formData.shop.isOpen.toString());
    form.append("notes", formData.shop.notes);
    formData.shop.shopImage.images.forEach((file: any) => {
      form.append("shopImages", file.raw);
    });
    formData.shop.certificateImage.images.forEach((file: any) => {
      form.append("certificateImages", file.raw);
    });

    const res = await addCarShop(form);
    if (res.code === 0) {
      toast.success("添加成功");
      dialogVisible.shopForm = false;
      pageData.flag = !pageData.flag;
      Object.assign(generatedAccount, res.data);
      dialogVisible.accountInfo = true;
    }
  } catch (error) {
    toast.error("操作失败");
  }
};

const resetShopForm = () => {
  shopFormRef.value?.resetFields();
  formData.shop = {
    name: "",
    type: "",
    startTime: "",
    endTime: "",
    operatingHours: "",
    phone: "",
    email: "",
    postalCode: "",
    provinceCityCounty: [],
    address: "",
    openingDate: "",
    managerName: "",
    website: "",
    isSelf: 0,
    isOpen: 1,
    notes: "",
    categoryList: [],
    categoryLoading: false,
    shopImage: {
      handlePictureCardPreview: (uploadFile: any) => {
        formData.shop.shopImage.dialogImageUrl = uploadFile.url!;
        formData.shop.shopImage.dialogVisible = true;
      },
      images: [],
      dialogVisible: false,
      dialogImageUrl: "",
    },
    certificateImage: {
      handlePictureCardPreview: (uploadFile: any) => {
        formData.shop.certificateImage.dialogImageUrl = uploadFile.url!;
        formData.shop.certificateImage.dialogVisible = true;
      },
      images: [],
      dialogVisible: false,
      dialogImageUrl: "",
    },
  } as ShopForm;
};

// 初始化
onMounted(() => {
  if (route.path.startsWith("/Product/CarShops")) {
    pageData.activeTab = 1;
  }
  fetchShopList();
  loadShopCategories();
});

// 监听器
watch(
  [
    () => pageData.pagination.currentPage,
    () => pageData.pagination.pageSize,
    () => pageData.searchKey,
    () => pageData.flag,
  ],
  fetchShopList
);
</script>

<style scoped>
/* 保持原有样式不变 */
.scroll-bar {
  height: calc(100vh - 262px);
  padding: 0 12px;
}
.form {
  width: 100%;
}
.form-item {
  width: calc(50% - 34px);
}
.form-item2 {
  width: calc(100% - 34px);
}
.operation-btn {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}
.account-info {
  padding: 20px;
}
.info-item {
  margin: 15px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
